<template>
  <div class="container">
    <div class="app-container">
      <!-- 添加权限按钮 -->
      <div style="padding: 10px">
        <el-button type="primary" size="mini" @click="addPermission('add', 0)">添加权限</el-button>
      </div>
      <!-- 权限数据表格 -->
      <el-table :data="perList" row-key="id" default-expand-all>
        <el-table-column prop="name" label="名称" />
        <el-table-column prop="code" label="标识" />
        <el-table-column prop="description" label="描述" />
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button v-if="row.type === 1" type="text" size="mini" @click="addPermission('add',row.id)">添加</el-button>
            <el-button type="text" size="mini" @click="addPermission('edit', row.id)">编辑</el-button>
            <el-button type="text" size="mini" @click="deletePermission(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 权限弹层 -->
    <per-dialog ref="perDialog" :show-dialog.sync="showDialog" :current-id="currentId" :type="type" @updatePer="getPermissionsList" />
  </div>
</template>
<script>
import { deletePermissionAPI, getPermissionsListAPI } from '@/api/permission'
import { transListToTreeData } from '@/utils'
import perDialog from './components/perDialog.vue'
export default {
  name: 'Permission',
  components: { perDialog },
  data() {
    return {
      perList: [], // 权限点列表
      showDialog: false, // 弹层开关
      currentId: null,
      type: ''
    }
  },
  created() {
    // 获取权限点列表
    this.getPermissionsList()
  },
  methods: {
    // 添加权限点
    addPermission(type, id) {
      if (type === 'add') {
        // 打开弹层
        this.showDialog = true
        this.currentId = id
        this.type = type
      } else if (type === 'edit') {
        console.log(id)
        this.showDialog = true
        this.currentId = id
        this.type = type
        this.$nextTick(() => {
          this.$refs.perDialog.getPermissionsDetail()
        })
      }
    },
    // 删除权限点
    deletePermission(row) {
      // console.log(row.id)
      // 弹出提示框
      this.$confirm('您确定要删除此权限点吗', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(async() => {
        // 调用删除权限接口
        await deletePermissionAPI(row.id)
        // 重新获取权限点列表
        this.getPermissionsList()
        // 提示用户删除成功
        this.$message.success('删除权限成功')
      })
    },
    // 调用权限点列表
    async getPermissionsList() {
      this.perList = transListToTreeData(await getPermissionsListAPI())
    }
  }
}
</script>
